// index.js
import api from "../../config/api";
import {
	getUserLocation,
	getUserPermissions,
	shareOptions,
	logout
} from "../../utils/access";
import request from "../../utils/request";
import {
	getBarAndTitleHeight,
	getXsScreen,
	getStorage,
	setStorage,
	removeStorage,
	jump,
	jumpUrl,
	formatDate
} from "../../utils/utils";
const app = getApp();

Page({
	data: {
		//广告ID数据
		ADkey: '',
		// 模板数据
		templateList: [],
		//服务器异常
		isError: false,
		// 用户首页数据
		infoData: null,
		// 轮播图数据
		bannerList: [],
		// 导航栏数据-目标小区
		navbarList: [{
				title: '上门回收',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/glBLNp4wXre3e3ab1652664e7fa99362615ebc975af3.png',
				path: 'recycle'
			},
			{
				title: '大件代扔',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/HNUW8qboM0wha968a80c69359833937dddcef7413436.png',
				path: 'recycleFurniture'
			},
			{
				title: '答题测试',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/wSFF55YzQjKfd2002bc30ae673c68897d7605281d01e.png',
				path: 'test'
			},
			{
				title: '习惯养成',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/MDPnsQNWvq5U37c6405efdab2095476071df538e415b.png',
				path: 'habit'
			}
		],
		// 导航栏数据-非目标小区
		navbarNormalList: [{
				title: '签到日历',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/pMcK0Mq9axje51441e48d7ef406da0e8b7d7d79e8090.png',
				path: 'openScreen'
			},
			{
				title: '答题测试',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/GNA1L8keBXHI80ed5a50f4985ca496b63a8f6b70073e.png',
				path: 'test'
			},
			{
				title: '分类知识',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/jKaFiiUADIjL9c17f17c348aa799ef9c9baa25134562.png',
				path: 'learn'
			},
			{
				title: '邀请好友',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/4AbF1LFiBA66547c40b569ff1c77e5e96a780564579b.png',
				path: 'invite'
			}
		],
		// 活动数据
		activityList: [],
		// 闲置好物数据
		idleList: [],
		// 分类工具箱数据
		toolList: [{
				title: '桶内识别',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/7Cic3DBuNJhlbb21da162a718232406639c03d2596b8.png',
				desc: '桶内成分一次分析',
				path: 'categoryPhoto',
				params: ''
			},
			{
				title: '拍照分类',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/VtzAenJDucKZceab22b4f18ba3b7c3cb5add432b92cd.png',
				desc: '随手拍拍领好礼',
				path: 'categoryPhoto',
				params: {
					isAny: 1
				}
			},
			{
				title: '习惯养成',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/q7eC5ajXSEyc7e402769eb2709c30d052d917747a716.png',
				desc: '好习惯终生受益',
				path: 'habit',
				params: ''
			},
			{
				title: '答题测试',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/YMi5xH7q4OwI86a8a4856dc60678ffbfcb3710ff639c.png',
				desc: '测测你的分类知识',
				path: 'test',
				params: ''
			},
			{
				title: '定制提醒',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/7o7TGMuupEIh04ddc02956706cbc998cda00f0e8de67.png',
				desc: '不错过每次签到',
				path: 'timeRemind',
				params: ''
			},
			{
				title: '知识分类',
				icon: 'https://image-classify.daieco.com/kejian-quanzi/BcuaXC4XG3gSf908dc03fad21b39968cad7845285b51.png',
				desc: '扩充储备时间到',
				path: 'learn',
				params: ''
			}
		],
		// 未登录信息
		noLoginInfo: {
			avatarUrl: "https://image-classify.daieco.com/kejian-quanzi/3epbosyh2vtW3fcf5df33fa3b70ee2dc224ed84c4076.png",
			nickName: "未登录",
		},
		// 用户信息
		userInfo: {},
		// 是否登录
		isLogin: false,
		// 是否是目标小区
		isTargetCommunity: false,
		// 状态栏&标题栏高度
		...getBarAndTitleHeight(true),
		// 展示功能引导弹窗
		showFunctionModal: false,
		showFunctionSign: true, //功能引导-签到
		// 引流弹窗图片
		drainageQrcode: 'https://image-classify.daieco.com/kejian-quanzi/wNKGLsFGwRe08ebbcf449fefedb6810f667865662821.png'
	},
	// 是否显示活动弹窗
	activityShow: false,
	// 是否显示签到弹窗
	signShow: false,
	// 生命周期函数--监听页面加载
	onLoad(options) {
		if (options.scene) {
			var scene = decodeURIComponent(options.scene);
			console.log("scene is ", scene);
			if (scene) {
				var arr = scene.split("=");
				console.log("setStorageSync:", arr[0], "=", arr[1]);
				setStorage(arr[0], arr[1])
				if (app.isLogin()) {
					this.needSupply(arr[1])
					this.setData({
						isLogin: true
					})
				}
			}
		} else {
			const inviteUserId = options.invite_user_id || app.globalData.invite_user_id
			console.log("hition===邀请人用户id", inviteUserId);
			if (inviteUserId) {
				if (app.isLogin()) {
					this.needSupply(inviteUserId)
					this.setData({
						isLogin: true
					})
				}
				setStorage('invite_user_id', inviteUserId)
				app.globalData.invite_user_id = null
			}
		}

		if (options?.inviteData) {
			setStorage('inviteData', options?.inviteData)
			console.log('分享人数据：', options.inviteData)
		}
		const platform = options?.platform || app.globalData.platform
		if (platform) {
			setStorage('platform', platform)
			console.log('平台推广码数据：', platform)
		}
		// 是否是小屏幕尺寸
		let isXsScreen = getXsScreen().isXsScreen
		this.setData({
			isXsScreen,
			...getBarAndTitleHeight(),
		})
	},

	// 获取广告数据
	async getADData() {
		const res = await request.get(api.getAdShowData, {}, {
			loading: false
		})
		console.log('guanggao', res);
		if (res.httpStatus === 200) {

			let item = res.data.find((item) => {
				return item.advertSpace === 1
			})
			console.log('item', item);
			this.setData({
				ADkey: item ? item.advertId : ''
			})
		}
	},

	// 邀请码或分享链接过来的未认证居住地，跳转居住认证地页面
	async needSupply(uId) {
		const {
			data
		} = await request.get(api.needSupply, {
			'userId': uId
		})
		// if (data) {
		// 	wx.navigateTo({
		// 		url: `/pages/residenceCertification/residenceCertification?isComplete=${data}`
		// 	})
		// }
	},

	// 生命周期函数--监听页面显示
	async onShow() {
		// 判断是否展示消息红点
		let newMsgNum = getStorage('newMsgNum')
		if (!newMsgNum) {
			this.handleShowMessage()
		}

		this.getTabBar?.()?.setData?.({
			selected: 0,
			newMsgNum: newMsgNum ? newMsgNum : 0
		})
		const isLogin = app.isLogin()
		// 未登录展示去签到弹窗
		if (!isLogin) {
			const signMadalDate = getStorage("signMadalDate") || '';
			const date = formatDate(new Date());
			this.signShow = signMadalDate != date
			const newSignMadalDate = date;
			setStorage("signMadalDate", newSignMadalDate);
			if (this.signShow && this.signModal) {
				this.signModal.show()
				this.signShow = false
			}
		} else {
			// 查询是否为郑州人
			let res = await request.get(api.userIsZhengzhou, {}, {
				loading: false
			})
			// 已登陆所有用户展示一次内容引导
			this.contentMadalShow = !getStorage("contentMadalShow")
			setStorage('contentMadalShow', true)
			//‘居住地认证为郑州’  每日展示一次小鹿闲置引流弹窗
			const drainageMadalDate = getStorage("drainageMadalDate") || '';
			const date = formatDate(new Date());
			this.drainageShow = drainageMadalDate != date && res.data
			setStorage("drainageMadalDate", date);
			if (this.contentMadalShow) {
				if (this.contentModal) {
					this.contentModal.show()
					this.contentMadalShow = false
				}
			} else {
				if (this.drainageShow && this.drainageModal) {
					this.miniGoodsDataLogSave(6)
					this.drainageModal.show()
					this.drainageShow = false
				}
			}
		}
		this.getTemplateList()
		this.getUserData();
		this.getBannerList()
		this.getActivityList();
		this.getIdleList()
		this.setData({
			userInfo: isLogin ? app.userInfo() : this.data.noLoginInfo,
			isLogin: isLogin ? true : false
		})

		this.getADData()
	},

	adError(err){
		const { errMsg = '', errCode = '' } = err.detail || {}
		console.log(`广告加载失败: [${errCode}]${errMsg}`);
		this.setData({
			ADkey: ''
		})
	},
	// 是否展示消息红点
	async handleShowMessage() {
		const res = await request.get(api.isShowMessage, {}, {
			loading: false,
			modal: false
		})
		if (res.httpStatus === 200) {
			if (res.data) {
				setStorage('newMsgNum', 1)
				this.getTabBar?.()?.setData?.({
					newMsgNum: 1
				})
			}
		}
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		this.contentModal = this.selectComponent('#contentModal')
		this.signModal = this.selectComponent('#signModal')
		this.challengeModal = this.selectComponent('#challenge-modal')
		this.drainageModal = this.selectComponent('#drainageModal')
		if (this.signShow) {
			this.signModal.show()
			this.signShow = false
		}
		if (this.contentMadalShow) {
			this.contentModal.show()
			this.contentMadalShow = false
		} else {
			if (this.drainageShow) {
				this.drainageModal.show()
				this.miniGoodsDataLogSave(6)
				this.drainageShow = false
			}
		}
	},
	// 页面相关事件处理函数--监听用户下拉动作
	onPullDownRefresh() {

	},
	// 页面隐藏
	onHide() {

	},
	// 获取模板数据
	async getTemplateList() {
		let res = await request.get(api.templateList, {}, {
			loading: false
		})
		console.log('获取模板数据', res);
		if (res.httpStatus === 200) {
			this.setData({
				isError: false,
				templateList: res.data.mouldConfigVOS
			})
		} else {
			this.setData({
				templateList: [],
				isError: true,
			})
		}
	},
	// 服务异常重试
	async refresh() {
		if (this.loading) return
		this.loading = true
		this.setData({
			isError: false
		})
		await this.getTemplateList()
		await this.getUserData();
		await this.getBannerList()
		await this.getActivityList();
		await this.getIdleList();
		this.loading = false
	},
	// 获取首页数据
	async getUserData() {
		const res = await request.get(api.userMessage, {}, {
			loading: false
		})
		console.log(res, '====')
		const infoData = res?.data || {}

		console.log('data', infoData);
		// 设置是否是目标小区
		this.setData({
			infoData,
			isTargetCommunity: infoData?.target
		})
		this.getTabBar?.()?.setData?.({
			isTargetCommunity: infoData?.target
		})
		// 登录失效
		if (!infoData?.login) {
			this.setData({
				isLogin: false
			})
			logout()
		}
	},
	/**
	 * 获取轮播图列表
	 */
	async getBannerList() {
		const res = await request.get(api.circleAdSpace, {
			size: 999
		}, {
			loading: false
		})
		if (res.httpStatus == 200) {
			this.setData({
				bannerList: res?.data?.records || []
			})
		}
	},
	//获取活动列表
	async getActivityList() {
		const res = await request.get(api.activity, {
			page: 1,
			size: 5,
			type: 1
		}, {
			loading: false
		})
		if (res.httpStatus == 200) {
			this.setData({
				activityList: res?.data?.records || [],
			})
		}
	},
	// 查询闲置好物数据
	async getIdleList() {
		let params = {
			pageIndex: 1,
			pageSize: 10,
			sortType: 10
		}
		let res = await request.get(api.miniGoodsPage, params, {
			loading: false
		})
		if (res.httpStatus == 200) {
			this.setData({
				idleList: res?.data?.records
			})
		}
	},

	// 关闭内容引导弹窗
	contentModalClose() {
		this.contentModal.hide()
		this.setData({
			showFunctionModal: true
		})
	},
	// 关闭签到引导 打开测试引导
	functionSignHandle() {
		this.setData({
			showFunctionSign: false
		})
	},
	// 关闭引导
	functionAnswerHandle() {
		this.setData({
			showFunctionModal: false
		})
		// 展示小鹿闲置引流弹窗
		if (this.drainageShow) {
			this.drainageModal.show()
			this.miniGoodsDataLogSave(6)
			this.drainageShow = false
		}
	},

	// 关闭签到弹窗
	signModalClose() {
		this.signModal.hide()
	},
	// 跳转签到日历页
	jumpSignCalendar() {
		this.signModalClose()
		jump('openScreen')
	},
	// 关闭引流弹窗
	drainageModalClose() {
		this.drainageModal.hide()
		this.miniGoodsDataLogSave(4)
	},

	// 用户信息卡跳转
	jumpUserPath(e) {
		const {
			infoData
		} = this.data
		const {
			path,
			type
		} = e.currentTarget.dataset || {}

		// 未签到、去签到拍照
		if (type === 8) {
			jump(path, {
				source: 1,
				signDays: infoData.day
			})
			return
		}
		// 已签到，去拍照
		if (type === 9) {
			jump(path, {
				source: 2
			})
			return
		}

		// 跳转签到日历
		jump(path)
	},
	// 开启挑战弹窗
	openChallenge() {
		this.challengeModal.show();
	},
	// 开启挑战确认
	async challengeConfirm(e) {
		await request.get(api.startChallenge, null, {
			loading: false
		});
		e.detail.hide();
		jump("trophy");
	},

	// 轮播图跳转 
	async jumpBannerPath(e) {
		if (!e.currentTarget?.dataset?.path) return
		if (app.isLogin()) {
			wx.navigateTo({
				url: e.currentTarget.dataset.path
			})
		} else {
			const userInfo = await app.login()
			if (app.isLogin()) {
				// 获取首页数据
				this.getUserData()
				this.setData({
					isLogin: true
				})
			}
			this.setData({
				userInfo,
			})
		}
	},
	// 判断是否开启挑战
	async checkChallengeStatus() {
		if (app.isLogin()) {
			const res = await request.get(api.checkIsFail, null, {
				loading: false
			})
			// 0需要补救 1进行中 2成功 3失败 4无任务
			if ([2, 3, 4].includes(res?.data?.status)) {
				this.openChallenge()
			} else {
				wx.navigateTo({
					url: `/pages/trophy/trophy`,
				})
			}
		} else {
			jumpUrl(path)
		}
	},
	// 检验登录、位置授权
	async checkAuch(isLogin, isLocation, path) {
		console.log('isLogin,isLocation,path', isLogin, isLocation, path)
		if (isLogin === 1 && !app.isLogin()) {
			const userInfo = await app.login()
			if (app.isLogin()) {
				// 获取首页数据
				this.getUserData()
				this.setData({
					isLogin: true
				})
			}
			this.setData({
				userInfo,
			})
			return
		}
		if (isLocation === 1 && !getUserLocation()) {
			getUserPermissions('userLocation', (res) => {
				if (res) {
					// 测试
					if (path.startsWith('/pages/test/test')) {
						removeStorage('fromActivity')
					}
					// 21天任务挑战 查询挑战任务状态 已开启去挑战任务列表 未开启显示弹窗
					if (path.startsWith('/pages/trophy/trophy')) {
						this.checkChallengeStatus(path)
						return
					}
					jumpUrl(path)
				}
			})
			return
		}
		// 测试
		if (path.startsWith('/pages/test/test')) {
			removeStorage('fromActivity')
		}
		// 21天任务 挑战查询挑战任务状态 已开启去挑战任务列表 未开启显示弹窗
		if (path.startsWith('/pages/trophy/trophy')) {
			this.checkChallengeStatus(path)
			return
		}
		jumpUrl(path)
	},
	// 金刚区跳转
	async jumpNavbarPath(e) {
		let {
			path,
			islogin,
			islocation
		} = e.currentTarget.dataset
		this.checkAuch(islogin, islocation, path)
	},

	// 个人中心跳转
	async jumpMinePath() {
		if (app.isLogin()) {
			jump('mine')
		} else {
			const userInfo = await app.login()
			if (app.isLogin()) {
				// 获取首页数据
				this.getUserData()
				this.setData({
					isLogin: true
				})
			}
			this.setData({
				userInfo
			})
		}
	},

	// 活动页跳转
	jumpActivityPath(e) {
		let path = e.currentTarget.dataset.path || ''
		let source = e.currentTarget.dataset.source || ''
		let id = e.currentTarget.dataset.id || ''
		if (source === 2) {
			if (!path) return
			jumpUrl(path)
		} else {
			if (!id) return
			jump('activityDetail', {
				id
			})
		}
	},

	// 便民服务跳转
	async jumpConveniencePath(e) {
		let {
			path,
			islogin,
			islocation
		} = e.currentTarget.dataset
		this.checkAuch(islogin, islocation, path)
	},
	// 分类工具箱跳转
	async jumpToolPath(e) {
		let {
			path,
			islogin,
			islocation
		} = e.currentTarget.dataset
		this.checkAuch(islogin, islocation, path)
	},
	// 跳转到本地好物页面
	jumpIdleHome() {
		if (app.isLogin()) {
			jump('fawnIdleHome')
		} else {
			app.login()
		}
	},
	// 跳转到小鹿闲置小程序
	jumpIdleApplet(e) {
		let id = e.currentTarget.dataset.id
		if (app.isLogin()) {
			const {
				loadMiniProgram
			} = this.data
			if (loadMiniProgram) return
			this.setData({
				loadMiniProgram: true,
			})
			this.miniGoodsDataLogSave(2)
			//不是代代回收用户，跳转代代回收小程序完成注册
			wx.navigateToMiniProgram({
				appId: 'wx5a2f319913b5b3e9',
				path: `pages/goodsDetails/goodsDetails?source=QD000001&goodsId=${id}`,
				envVersion: 'trial',
				success: () => {
					console.log('跳转成功')
					this.miniGoodsDataLogSave(3)
				},
				fail: (error) => {
					console.log('跳转失败', error)
					if (error?.errMsg !== 'navigateToMiniProgram:fail cancel') {
						wx.showToast({
							title: '跳转失败，请重试',
							icon: 'none',
						})
					}
				},
				complete: () => {
					this.setData({
						loadMiniProgram: false,
					})
				},
			})
		} else {
			app.login()
		}
	},
	// 保存图片
	handleSavePhoto() {
		if(this.loading) return
		this.loading = true
		let that = this
		wx.getImageInfo({
			src: this.data.drainageQrcode,
			success: function (sres) {
				// 调用系统方法，下载图片并保存
				getUserPermissions(
					'writePhotosAlbum',
					(res) => {
						if (res) {
							wx.showToast({
								title: '保存成功',
								icon: 'success',
							})
							that.miniGoodsDataLogSave(5)
							that.drainageModal.hide()
							this.loading = false
						} else {
							wx.showToast({
								title: '保存失败',
								icon: 'error',
							})
							this.loading = false
						}
					}, {
						filePath: sres.path
					}
				)
			},
		})
	},
	async onPullDownRefresh() {
		await this.getTemplateList()
		await this.getUserData();
		await this.getBannerList()
		await this.getActivityList();
		await this.getIdleList();
		wx.stopPullDownRefresh()
	},
	// 引流弹窗、小鹿闲置小程序跳转弹窗数据统计
	miniGoodsDataLogSave(type) {
		request.post(api.miniGoodsDataLogSave, {
			type
		}, {
			loading: false
		})
	},
	// 页面滚动事件
	onPageScroll(e) {

	},
	// 禁止拖动
	activityMove() {},
	// 用户点击右上角分享
	onShareAppMessage(e) {
		return shareOptions('default', e)
	},
});